package cn.bellychang.anemicVsdomain.anemic;

import cn.bellychang.anemicVsdomain.RecognitionDao;
import org.joda.money.Money;

import java.math.RoundingMode;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;

/**
 * 在anemic model中 service层定义了 how + what
 * @author ChangLiang
 * @date 2020/5/18
 */
public class RecognitionService {

    private RecognitionDao recognitionDao = new RecognitionDao();

    /**
     * 计算应收账：这里收入确认规则比较简单，仅仅与产品有关
     * 如果这里有复杂的逻辑，不仅仅与产品有关，还有签订合同的日期相关，与签订合同的地域相关 那就非常复杂了
     * @param contractId
     */
    public void calculateRevenueRecognition(Long contractId) {
        Contract contract = recognitionDao.findContractById(1L);
        Money revenue = contract.getRevenue();
        Long productId = contract.getProductId();
        Date signedDate = contract.getSignedDate();
        Money temp;
        switch (recognitionDao.getProductNameByProductId(productId)) {
            case SpreadSheet:
                temp = revenue.dividedBy(3, RoundingMode.UNNECESSARY);
                recognitionDao.insertRevenueRecognition(contractId,temp,signedDate);
                recognitionDao.insertRevenueRecognition(contractId,temp,Date.from(Instant.now().plus(60, ChronoUnit.DAYS)));
                recognitionDao.insertRevenueRecognition(contractId,temp,Date.from(Instant.now().plus(90, ChronoUnit.DAYS)));
                break;
            case Word:
                recognitionDao.insertRevenueRecognition(contractId,revenue,signedDate);
                break;
            case Database:
                temp = revenue.dividedBy(3, RoundingMode.UNNECESSARY);
                recognitionDao.insertRevenueRecognition(contractId,temp,signedDate);
                recognitionDao.insertRevenueRecognition(contractId,temp,Date.from(Instant.now().plus(30, ChronoUnit.DAYS)));
                recognitionDao.insertRevenueRecognition(contractId,temp,Date.from(Instant.now().plus(60, ChronoUnit.DAYS)));
            default:
                break;
        }
    }

    /**
     * query contract revenue till asOfDate
     * @param contractId if contractId==null, then calculate all contracts, else do assigned contract
     * @param asOfDate
     * @return
     */
    public Money getRecognizedRevenue(Date asOfDate, Long contractId) {
        return recognitionDao.getRecognitionListByDate(asOfDate, contractId);
    }
}
